const jwt = require('jsonwebtoken');
const expressJWT = require('express-jwt');
const logger = require('./logger-util');
const db = require('../models/index');
const Users = db.users;
const Roles = db.roles;
const Menus = db.menus;
const rolesMenus = db.rolesMenus;

// 创建token
const createToken = (data, exp) => {
    let obj = {};
    obj.data = data ? data : null;
    obj.type = 'jsonwebtoken';
    obj.ctime = new Date().getTime(); // token创建时间
    exp = exp ? exp : 60 * 60 * 24; // 设定过期时间，默认为1天
    let token = jwt.sign(obj, process.env["SIGN_KEY"], { expiresIn: exp });
    token = 'Bearer ' + token;
    return token;
};

// 验证
const varifyToken = expressJWT({
    secret: process.env["SIGN_KEY"],
    algorithms: ['HS256'],
    // requestProperty:'auth', //自定义获取的信息位置，默认验证通过req.user获取token信息
    credentialsRequired: true, //是否允许无token请求
}).unless({
    path: [
        { url: '/api/private/users/register', methods: ['POST'] }, // 白名单
    ]
});

// 许可
const permissionAuth = async (req, res, next) => {
        // const userInfo = req.user.data;
        // //请求的接口
        // const reqPath = `${req.method} ${req.baseUrl}`;
        // // 查询用户信息
        // let resUserInfo = await Users.findOne({where: { id:userInfo.id }});
        // let params = {
        //     where: { id:resUserInfo.roleId },
        //     raw: false,
        //     include: [
        //         {model: Menus}
        //     ]
        // };
        // let roleInfo = await Roles.findOne(params);
        // let userMenus = roleInfo.menus || [];
        // console.log('数据==========',roleInfo);
        next();
    
};

// 失败处理--放到最后一个app.use()
const errorToken = (err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
        // 打印日志
        logger.error(`${req.method} ${req.baseUrl + req.path} === 响应：${JSON.stringify({
            data: null,
            code: err.status || 401,
            message: err.message || 'token错误'
        })}`);
        // 返回失败信息
        res.status(401).send({
            data: null, 
            code: err.status || 401, 
            message: err.message || 'token错误'
        });
    };
};


module.exports = {
    createToken,
    varifyToken,
    permissionAuth,
    errorToken
};